/**
 * 通过AsyncTask发送GET请求，并通过InputStream返回获取到的数据。
 * 若获取失败，则返回NULL
 * Update:2014/04/21
 * @author 程文智
 */
package com.taxsystem.tool;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.Log;

/**
 * 通过 HttpClient 发送GET请求，并通过InputStream返回数据。
 * @author 程文智
 * @version 1
 */
public class GetRequestTask extends AsyncTask<String, Void, InputStream> {
	
	private final static String TAG = "GetRequestTask";
	
	@Override
	protected InputStream doInBackground(String... urlStr) {
		try {
			URL url = new URL(urlStr[0]);
			
			HttpGet httpRequest = null;

			try {
			    httpRequest = new HttpGet(url.toURI());
			} catch (URISyntaxException e) {
			    e.printStackTrace();
			}

			HttpClient httpclient = new DefaultHttpClient();
			HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
			HttpEntity entity = response.getEntity();
			
			if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK){
				Log.e(TAG,"GET status code = "+ response.getStatusLine().getStatusCode());
				return null;
			}
			
			Log.v(TAG,"send GET request succeed");
			BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);

			InputStream is = bufHttpEntity.getContent();
			
			entity.consumeContent();
				
			if (null == is)
				Log.e(TAG,"sendGETRequest(): InputStream is is null");
			return is;
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}


}
